<template>
  <div class="app-container">
    <!-- 搜索 -->
    <el-card class="box-card">
      <el-row type="flex" align="middle">
        <el-col :span="12">
          <div class="grid-content bg-purple search">
            <el-form ref="query" :model="query" label-width="100px">
              <el-form-item style="margin-bottom:0px" label="名称">
                <i slot="label" class="el-icon-search" style="font-size:20px"></i>
                <el-input style="width:360px" v-model="query.keywords" placeholder="请输入合成名称/价格"></el-input>
              </el-form-item>
            </el-form>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="grid-content bg-purple-light" style="text-align:right">
            <el-button type="primary" @click="queryAsk">查询</el-button>
            <el-button @click="queryReset">重置</el-button>
          </div>
        </el-col>
      </el-row>
    </el-card>
    <!-- 表格 -->
    <el-card class="box-card">
      <img
        class="watermark"
        style="right: 0;"
        v-if="baseApi== 'https://testouhun.wm2177.com'"
        src="@/assets/watermark.png"
      />

      <el-button type="primary" style="margin-bottom:20px" @click="addList">添加</el-button>
      <el-table
        :data="tableData"
        :header-cell-style="{background:'#eee'}"
        border
        style="width: 100%;margin-bottom: 20px;"
        v-loading="loading"
      >
        <el-table-column align="center" type="index" width="50" label="序号"></el-table-column>
        <el-table-column align="center" label="合成图片">
          <template slot-scope="scope">
            <el-popover placement="top-start" title trigger="hover">
              <img :src="scope.row.compound_img" alt style="max-width:150px" />
              <!-- <el-avatar shape="square" :size="150" fit="cover" :src="scope.row.img"></el-avatar> -->
              <el-avatar
                slot="reference"
                shape="square"
                :size="50"
                fit="scale-down"
                :src="scope.row.compound_img"
              ></el-avatar>
              <!-- <img
                slot="reference"
                :src="scope.row.img"
                style="width: 60px;height: 60px"
              />-->
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="goods_name" label="名称"></el-table-column>
        <el-table-column align="center" prop="price" label="原价" sortable></el-table-column>
        <el-table-column align="center" label="每人限合成数量">
          <template slot-scope="scope">
            <div v-if="scope.row.num==0">无限制</div>
            <div v-if="scope.row.num!=0">{{scope.row.num}}</div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="上架">
          <template slot-scope="scope">
            <div v-if="scope.row.is_show==1">上架</div>
            <div v-if="scope.row.is_show==0">下架</div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="推荐">
          <template slot-scope="scope">
            <div v-if="scope.row.is_tui==0">否</div>
            <div v-if="scope.row.is_tui==1">是</div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="预售">
          <template slot-scope="scope">
            <div v-if="scope.row.type==1">预售</div>
            <div v-if="scope.row.type==2">现货</div>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="sum" label="合成总数"></el-table-column>
        <el-table-column align="center" prop="sort" label="排序"></el-table-column>
        <el-table-column align="center" prop="add_time" label="添加时间" sortable></el-table-column>
        <el-table-column align="center" prop="update_time" label="更新时间" sortable></el-table-column>
        <el-table-column align="center" fixed="right" label="操作" width="150">
          <template slot-scope="scope">
            <el-button @click="handleEdite(scope.row)" type="text" size="small">编辑</el-button>
            <el-popconfirm
              confirmButtonText="好的"
              cancelButtonText="不用了"
              icon="el-icon-info"
              iconColor="red"
              title="这是一段内容确定删除吗？"
              @onConfirm="handleDel(scope.row)"
            >
              <el-button
                style="margin-left:10px;color:red"
                slot="reference"
                type="text"
                size="small"
              >删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <div style="text-align:right">
        <el-pagination
          background
          layout="prev, pager, next"
          :current-page="currentPage"
          :total="total"
          @current-change="currentChange"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 抽屉 -->
    <el-drawer
      :title="title"
      :visible.sync="drawer"
      :direction="direction"
      :before-close="handleClose"
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="150px"
        style="margin-left:10px;"
      >
        <el-form-item label="奖品" prop="goods_id">
          <el-button type="primary" @click="chooseGood">选择奖品</el-button>
        </el-form-item>
        <el-form-item label="奖品图片" v-if="goods.img">
          <el-avatar shape="square" :size="100" fit="fill" :src="goods.img"></el-avatar>
        </el-form-item>
        <el-form-item label="奖品名称" v-if="goods.goods_name">
          <div>{{goods.goods_name}}</div>
        </el-form-item>
        <el-form-item label="是否为虚拟商品" prop="virtual">
          <el-radio-group v-model="form.virtual">
            <el-radio label="0">实物</el-radio>
            <el-radio label="1">虚拟</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="商品虚拟价值" prop="balance" v-if="form.virtual==1">
          <el-input-number
            :controls="false"
            style="width:360px"
            v-model="form.balance"
            placeholder="请输入虚拟价值"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="奖品单价" v-if="goods.price">
          <div>{{goods.price}}</div>
        </el-form-item>
        <el-form-item label="上传合成奖品图片" prop="compound_img">
          <el-upload
            class="avatar-uploader"
            action="https://upload-z0.qiniup.com/"
            :data="postData"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="合成总数" prop="sum">
          <el-input style="width:360px" v-model="form.sum" placeholder="请输入合成总数"></el-input>
        </el-form-item>
        <el-form-item label="每人限制数量" prop="num">
          <el-input style="width:360px" v-model="form.num" placeholder="请输入每人限制数量0为无限"></el-input>
        </el-form-item>
        <el-form-item label="是否上架" prop="is_show">
          <el-select v-model="form.is_show" placeholder="请选择是否上架" style="width:360px">
            <el-option label="下架" value="0"></el-option>
            <el-option label="上架" value="1"></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="是否推荐" prop="is_tui">
          <el-select v-model="form.is_tui" placeholder="请选择是否推荐" style="width:360px">
            <el-option label="是" value="1"></el-option>
            <el-option label="否" value="0"></el-option>
          </el-select>
        </el-form-item>-->
        <el-form-item label="排序" prop="sort">
          <el-input style="width:360px" v-model="form.sort" placeholder="请输入排序，越大越靠前"></el-input>
        </el-form-item>
        <el-form-item label="库存" prop="kc">
          <el-input style="width:360px" v-model="form.kc" placeholder="请输入库存"></el-input>
        </el-form-item>
        <!-- <el-form-item label="排序" prop="sort">
          <el-input style="width:360px" v-model="form.sort" placeholder="请输入排序"></el-input>
        </el-form-item>-->
        <el-form-item>
          <el-button type="primary" @click="onSubmit">确定</el-button>
          <el-button @click="subCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>

    <!-- 选择奖品 -->
    <el-dialog
      title="选择奖品"
      :visible.sync="dialogVisible"
      width="60%"
      :before-close="dialoghandleClose"
    >
      <div class="query-card">
        <div class="grid-content bg-purple search">
          <el-form ref="dialogquery" :model="dialogquery" label-width="100px" style="display:flex;">
            <el-form-item style="margin-bottom:0px" label="商品名称">
              <el-input style="width:260px" v-model="dialogquery.keywords" placeholder="请输入商品名称"></el-input>
            </el-form-item>
            <el-form-item style="margin-bottom:0px" label="商品分类">
              <el-cascader
                @focus="getCategary"
                v-model="dialogquery.class_id"
                :options="dialogoptions"
                :props="{ checkStrictly: true,value:'id',label:'class_name' }"
                placeholder="请选择奖品分类"
                clearable
                :loading="queryLoading"
              ></el-cascader>
            </el-form-item>
          </el-form>
        </div>
        <div class="grid-content bg-purple-light" style="text-align:right">
          <el-button type="primary" @click="dialogqueryAsk">查询</el-button>
          <el-button @click="dialogqueryReset">重置</el-button>
        </div>
      </div>
      <el-table
        :data="goodsData"
        ref="sendmultipleTable"
        border
        tooltip-effect="dark"
        style="width: 100%;margin: 20px 0;"
        @row-click="handleSelectionChange"
        :header-cell-style="{background:'#eee'}"
      >
        <el-table-column align="center" width="55">
          <template slot-scope="scope">
            <el-radio v-model="sendForm.goods_id" :label="scope.row.id">{{""}}</el-radio>
          </template>
        </el-table-column>
        <el-table-column align="center" type="index" width="50" label="序号"></el-table-column>

        <el-table-column align="center" prop="goods_name" label="商品名称"></el-table-column>
        <el-table-column align="center" label="商品图片">
          <template slot-scope="scope">
            <el-popover placement="top-start" title trigger="hover">
              <img :src="scope.row.img" alt style="max-width:150px" />
              <el-avatar
                slot="reference"
                shape="square"
                :size="50"
                fit="scale-down"
                :src="scope.row.img"
              ></el-avatar>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="class_name" label="分类"></el-table-column>
        <el-table-column align="center" prop="price" label="单价"></el-table-column>
      </el-table>
      <div style="text-align:right">
        <el-pagination
          background
          layout="prev, pager, next"
          :current-page="dialogcurrentPage"
          :total="dialogtotal"
          @current-change="dialogcurrentChange"
        ></el-pagination>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="goodsInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from '@/api/qiniu'
import {
  synthesisList,
  delSynthesis,
  addSynthesis,
  editSynthesis
} from '@/api/synthesis'
import { categoryList } from '@/api/product'
import { boxRewardList } from '@/api/boxreward'
import { parseTime } from '@/utils/index'

export default {
  name: 'SynthesisList',
  data() {
    return {
      baseApi: process.env.VUE_APP_BASE_API,
      // 分页数据
      total: 0,
      currentPage: 1,
      pageSize: 10,
      //input
      query: {
        keywords: ''
      },
      tableData: [],
      // 编辑抽屉
      drawer: false,
      direction: 'rtl',
      title: '编辑',
      form: {
        compound_img: '',
        goods_id: '',
        sum: '',
        num: '',
        is_show: '1',
        // is_tui: "",
        sort: '',
        kc: '',
        sort: '',
        virtual: '',
        balance: ''
      },
      rules: {
        virtual: [
          { required: true, message: '请选择商品属性', trigger: 'blur' }
        ],
        balance: [
          { required: true, message: '请输输入虚拟价值', trigger: 'blur' }
        ],
        compound_img: [
          { required: true, message: '请选择商品图片', trigger: 'blur' }
        ],
        goods_id: [
          { required: true, message: '请输选择奖品', trigger: 'blur' }
        ],
        sum: [{ required: true, message: '请输输入合成总数', trigger: 'blur' }],
        num: [
          { required: true, message: '请输输入没人限制数量', trigger: 'blur' }
        ],
        is_show: [
          { required: true, message: '请输选择是否上架', trigger: 'blur' }
        ],
        // is_tui: [
        //   { required: true, message: "请输选择是否推荐", trigger: "blur" }
        // ],
        sort: [{ required: true, message: '请输入排序', trigger: 'blur' }],
        kc: [{ required: true, message: '请输输入库存', trigger: 'blur' }],
        sort: [{ required: true, message: '请选输入排序', trigger: 'blur' }]
      },
      loading: false,
      selectLoading: false,
      options: [],
      dialogVisible: false,
      // 分页数据
      dialogtotal: 0,
      dialogcurrentPage: 1,
      dialogpageSize: 10,
      //input
      dialogquery: {
        keywords: '',
        class_id: ''
      },
      dialogoptions: [],
      queryLoading: false,
      goodsData: [],
      goods: '',
      sendForm: { goods_id: '' },
      // 上传图片
      url: '',
      imageUrl: '',
      postData: {
        token: ''
      }
    }
  },
  mounted() {
    this.getToken()
    this.getList()
  },
  methods: {
    //合成商品列表
    async getList() {
      this.loading = true
      const res = await synthesisList({
        page: this.currentPage,
        limit: this.pageSize,
        keywords: this.query.keywords
      })
      this.loading = false
      console.log(res)
      this.total = res.count
      this.tableData = res.data
      this.tableData.forEach((item) => {
        if (item.add_time == 0) {
          item.add_time = '-'
        } else {
          item.add_time = parseTime(item.add_time, '{y}-{m}-{d} {h}:{i}:{s}')
        }
        if (item.update_time == 0) {
          item.update_time = '-'
        } else {
          item.update_time = parseTime(
            item.update_time,
            '{y}-{m}-{d} {h}:{i}:{s}'
          )
        }
      })
    },
    // 获取商品分类
    async getCategary() {
      this.queryLoading = true
      const res = await categoryList({ page: 1, limit: 999, keywords: '' })
      console.log(res)
      this.dialogoptions = res.data
      this.queryLoading = false
    },
    //奖品列表
    async getRewardList() {
      const res = await boxRewardList({
        page: this.dialogcurrentPage,
        limit: this.dialogpageSize,
        keywords: this.dialogquery.keywords,
        class_id: this.dialogquery.class_id
      })
      this.goodsData = res.data
      this.dialogtotal = res.count
    },
    queryAsk() {
      this.currentPage = 1
      this.getList()
    },
    //重置
    queryReset() {
      this.resetForm('query')
      this.total = 0
      this.currentPage = 1
      this.pageSize = 10
      this.query.keywords = ''
      this.getList()
    },
    addList() {
      this.drawer = true
      this.title = '添加'
    },
    // 表格操作
    async handleDel(row) {
      try {
        const res = await delSynthesis({ id: row.id })
        console.log(res)
        this.getList()
        this.$message({
          message: '删除成功',
          type: 'success'
        })
      } catch (error) {
        this.$message.error('删除失败')
        console.log(error)
      }
    },
    handleEdite(row) {
      this.drawer = true
      this.title = '编辑'
      console.log(row)
      this.form.goods_id = row.goods_id
      this.sendForm.goods_id = row.goods_id
      this.form.sum = row.sum
      this.form.num = row.num
      this.form.is_show = row.is_show
      // this.form.is_tui = row.is_tui;
      this.form.sort = row.sort
      this.form.virtual = row.virtual
      this.form.balance = row.balance
      this.form.kc = row.kc
      this.form.sort = row.sort
      this.form.id = row.id
      this.form.compound_img = row.compound_img
      this.imageUrl = row.compound_img
      this.goods = row
    },
    //分页改变
    currentChange(current) {
      this.currentPage = current
      this.getList()
    },
    //抽屉
    handleClose(done) {
      this.resetForm('form')
      const form = {
        goods_id: '',
        sum: '',
        num: '',
        is_show: '',
        // is_tui: "",
        sort: '',
        kc: '',
        sort: '',
        id: '',
        virtual: '',
        balance: ''
      }
      this.goods = ''
      this.imageUrl = ''
      this.form = form
      this.drawer = false
      done()
    },
    subCancel() {
      this.resetForm('form')
      const form = {
        goods_id: '',
        sum: '',
        num: '',
        is_show: '',
        // is_tui: "",
        sort: '',
        kc: '',
        sort: '',
        id: '',
        type: '',
        balance: ''
      }
      this.goods = ''
      this.imageUrl = ''
      this.form = form
      this.drawer = false
    },
    onSubmit() {
      this.$refs['form'].validate(async (valid) => {
        if (valid) {
          if (this.title === '添加') {
            console.log(this.form)
            const res = await addSynthesis({ ...this.form })
            console.log(res)
            if (res.st === 1) {
              this.resetForm('form')
              const form = {
                goods_id: '',
                sum: '',
                num: '',
                is_show: '',
                // is_tui: "",
                sort: '',
                kc: '',
                sort: '',
                type: '',
                balance: ''
              }
              this.goods = ''
              this.imageUrl = ''
              this.form = form
              this.getList()
              this.$message({
                message: '添加成功',
                type: 'success'
              })
              this.drawer = false
            } else {
              console.log(res)
              this.$message.error('添加失败')
            }
          } else if (this.title === '编辑') {
            const res = await editSynthesis({ ...this.form })
            console.log(res)
            if (res.st === 1) {
              this.resetForm('form')
              const form = {
                goods_id: '',
                sum: '',
                num: '',
                is_show: '',
                // is_tui: "",
                sort: '',
                kc: '',
                sort: '',
                id: '',
                type: '',
                balance: ''
              }
              this.goods = ''
              this.imageUrl = ''
              this.form = form
              this.getList()
              this.$message({
                message: '编辑成功',
                type: 'success'
              })
              this.drawer = false
            } else {
              console.log(res)
              this.$message.error('编辑失败')
            }
          }
        }
      })
    },
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.drawer = false
    },
    // 选择商品
    dialoghandleClose() {
      this.dialogVisible = false
    },
    //分页改变
    dialogcurrentChange(current) {
      this.dialogcurrentPage = current
      this.getRewardList()
    },
    dialogqueryAsk() {
      this.dialogcurrentPage = 1
      this.dialogquery.class_id =
        this.dialogquery.class_id[this.dialogquery.class_id.length - 1]
      this.getRewardList()
    },
    //重置
    dialogqueryReset() {
      this.resetForm('dialogquery')
      this.dialogtotal = 0
      this.dialogcurrentPage = 1
      this.dialogpageSize = 10
      this.dialogquery.keywords = ''
      this.dialogquery.class_id = ''
      this.getRewardList()
    },
    handleSelectionChange(val) {
      console.log(val)
      this.goods = val
      this.sendForm.goods_id = val.id
    },
    goodsInfo() {
      this.form.goods_id = this.goods.id
      this.form.goods_name = this.goods.goods_name
      this.form.price = this.goods.price
      this.form.img = this.goods.img
      this.dialogVisible = false
    },
    chooseGood() {
      this.dialogVisible = true
      this.getRewardList()
    },
    // 上传图片
    async getToken() {
      const res = await getToken()
      this.postData.token = res.data.uptoken
      this.url = res.data.domain
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = this.url + res.key
      this.form.compound_img = this.imageUrl
    },
    beforeAvatarUpload(file) {
      //   const isJPG = file.type === "image/jpeg";
      //   if (!isJPG) {
      //     this.$message.error("上传头像图片只能是 JPG 格式!");
      //   }
      const isLt1M = file.size / 1024 / 1024 < 1

      if (!isLt1M) {
        this.$message.error('上传头像图片大小不能超过 1MB!')
        return
      }
    }
  }
}
</script>

<style lang='scss' scoped>
.query-card {
  display: flex;
  justify-content: space-between;
}
.box-card {
  margin-bottom: 20px;
}
.search {
  display: flex;
  align-items: center;
}
::v-deep .el-textarea__inner {
  width: 360px !important;
}
::v-deep .el-drawer.rtl {
  width: 650px !important;
  overflow: auto;
}

// 上传图片
::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>